package com.imoresoft.agile.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.imoresoft.agile.property.AppConstants;
import com.imoresoft.agile.property.SessionConstants;
import com.imoresoft.agile.top.TopConstants;

public class AuthFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setCharacterEncoding(AppConstants.APPLICATION_ENCODING);

		StringBuffer url = httpRequest.getRequestURL();
		if (url.indexOf("top.action") >= 0 || url.indexOf("notify.action") >= 0) {
			chain.doFilter(request, response);
			return;
		}

		HttpSession session = httpRequest.getSession(true);
		Object top = session.getAttribute(SessionConstants.SESSION_TOP);
		if (top == null) {
			boolean isAjaxRequest = isAjaxRequest(httpRequest);
			if (isAjaxRequest) {
				httpResponse
						.getWriter()
						.print(
								"{\"result\":{\"code\":-1,\"msg\":\"您已经太长时间没有操作,请刷新页面\"}}");
				return;
			}

			httpResponse.sendRedirect(TopConstants.TAOBAO_LOGIN_URL);
			return;
		}
		chain.doFilter(request, response);
		return;
	}

	/**
	 * 判断是否为Ajax请求
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 是true, 否false
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader("X-Requested-With");
		if (requestType != null && requestType.equals("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}

	public void init(FilterConfig config) throws ServletException {
	}

	public void destroy() {
	}
}
